package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.AppHttpCodeEnum;
import com.heima.common.dtos.PageResponseResult;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.exception.LeadNewsException;
import com.heima.common.minio.MinIOFileStorageService;
import com.heima.model.wemeida.dtos.WmLoginDto;
import com.heima.model.wemeida.dtos.WmMaterialDto;
import com.heima.model.wemeida.pojos.WmMaterial;
import com.heima.model.wemeida.pojos.WmNewsMaterial;
import com.heima.model.wemeida.pojos.WmUser;
import com.heima.utils.common.BCrypt;
import com.heima.utils.common.JwtUtils;
import com.heima.utils.common.RsaUtils;
import com.heima.utils.common.ThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.PrivateKey;
import java.util.*;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    private MinIOFileStorageService storageService;
    @Autowired
    private WmNewMaterialMapper wmNewMaterialMapper;

    @Override
    public ResponseResult<WmMaterial> uploadPicture(MultipartFile multipartFile) {
        //参数校验
        if (multipartFile == null) {
            throw new LeadNewsException(AppHttpCodeEnum.PARAM_INVALID);
        }

        //获取当前登录用户信息
        WmUser wmUser = (WmUser) ThreadLocalUtils.get();
        if (wmUser == null) {
            throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
        }

        //把文件存储到MinIO
        //生成随机文件名称
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //获取原名
        String originalFilename = multipartFile.getOriginalFilename();
        //获取后缀名
        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
        //文件名称
        String fileName = uuid + extName;

        try {
            String url = storageService.uploadImgFile("", fileName, multipartFile.getInputStream());

            //存储DB信息
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUserId(wmUser.getId());
            wmMaterial.setUrl(url);
            wmMaterial.setType((short) 0);
            wmMaterial.setIsCollection((short) 0);
            wmMaterial.setCreatedTime(new Date());
            save(wmMaterial);

            //返回素材对象
            return ResponseResult.okResult(wmMaterial);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public ResponseResult<List<WmMaterial>> findList(WmMaterialDto dto) {
        //参数校验
        dto.checkParam();

        //获取当前登录用户
        WmUser wmUser = (WmUser) ThreadLocalUtils.get();
        if (wmUser == null) {
            throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
        }

        //封装条件
        //分页
        IPage<WmMaterial> iPage = new Page<>(dto.getPage(), dto.getSize());

        //条件
        QueryWrapper<WmMaterial> queryWrapper = new QueryWrapper<>();
        //用户条件
        queryWrapper.eq("user_id", wmUser.getId());
        //是否收藏
        if (dto.getIsCollection() != null && dto.getIsCollection().equals((short) 1)) {
            queryWrapper.eq("is_collection", dto.getIsCollection());
        }
        //排序
        queryWrapper.orderByDesc("created_time");

        //执行条件查询
        iPage = page(iPage, queryWrapper);

        //封装结果返回
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) iPage.getTotal());
        pageResponseResult.setData(iPage.getRecords());
        pageResponseResult.setCode(AppHttpCodeEnum.SUCCESS.getCode());
        pageResponseResult.setErrorMessage(AppHttpCodeEnum.SUCCESS.getErrorMessage());

        return pageResponseResult;
    }

    @Override
    public ResponseResult updateCollect(Integer id, int collect) {
        WmMaterial wmMaterial = getById(id);

        if(wmMaterial==null){
            throw new LeadNewsException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        wmMaterial.setIsCollection((short)collect);
        updateById(wmMaterial);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult delPicture(Integer id) {
        WmMaterial wmMaterial = getById(id);

        if(wmMaterial==null){
            throw new LeadNewsException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //判断该素材是否被文章关联
        QueryWrapper<WmNewsMaterial> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("material_id",id);
        Integer count = wmNewMaterialMapper.selectCount(queryWrapper);

        if(count>0){
            throw new LeadNewsException(500,"该素材与文章有关联，无法删除");
        }

        //删除MinIO文件
        storageService.delete(wmMaterial.getUrl());

        //删除DB的记录
        removeById(id);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
